package cn.handong.tool.Java文件操作;

import org.junit.Test;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

import java.io.*;
import java.lang.annotation.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class 读写txt {
    /**
     * 逐行读取TXT
     * @throws IOException
     */
    @Test
    public void readTxtToObject() throws IOException {
        //绝对路径
//      String path = "C:\\Users\\sqkb8v\\Documents\\list.txt";
        String path = "list.txt"; //使用相对路径的话要放在和src同基本的文件夹
        BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(path)), StandardCharsets.UTF_8));
        String lineTxt;
        // 逐行读取
        while ((lineTxt = br.readLine()) != null) {
            System.out.println(lineTxt);
        }
        br.close();
    }

    /**
     * 写入txt
     * @throws FileNotFoundException
     */
    @Test
    public void readExcelAndWriteTxt() throws FileNotFoundException {
        //写入txt
        String folder = "C:\\Users\\sqkb8v\\IdeaProjects\\my-general-tool";
        String file = "test.txt";
        List<String> messageList = new ArrayList<>();
        messageList.add("流浪地球");
        messageList.add("战狼");
        messageList.add("吴京");
        messageList.add("沈腾");
        messageList.add("林俊杰");
        messageList.add("五月天");
        writeToTxt(folder, file, messageList);
    }

    public void writeToTxt(String folder, String file, List<String> messageList) throws FileNotFoundException {
        File files = new File(folder);
        files.mkdirs();

        FileOutputStream fos = new FileOutputStream(folder + File.separator + file);

        // 逐行写入
        PrintWriter pw = new PrintWriter(fos);
        for (String message : messageList) {
            pw.println(message);
        }
        pw.close();
    }
}